package com.example.myapplication

import android.app.Service
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.widget.Button
import com.example.total.R
import java.util.concurrent.TimeUnit
class Activity_My() : AppCompatActivity() {
    private lateinit var memoryCleaner: MemoryCleanerService

    // 添加无参构造函数
    constructor(memoryCleaner: MemoryCleanerService): this() {
        this.memoryCleaner = memoryCleaner
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my)

        // 启动 MemoryCleanerService
        startService(Intent(this, MemoryCleanerService::class.java))

        findViewById<Button>(R.id.back).setOnClickListener {
            // 返回MainActivity3
            val intent = Intent(this, MainActivity3::class.java)
            startActivity(intent)
        }

        findViewById<Button>(R.id.exit).setOnClickListener {
            // 关闭当前Activity
            finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()

        // 停止 MemoryCleanerService
        stopService(Intent(this, MemoryCleanerService::class.java))
    }
}
class MemoryCleanerService : Service() {
    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        // 清理内存操作

        // 5分钟后再次执行本Service的onStartCommand方法
        val delayMillis = TimeUnit.MINUTES.toMillis(5)
        Handler(Looper.getMainLooper()).postDelayed({
            startService(Intent(this, MemoryCleanerService::class.java))
        }, delayMillis)

        // 表示在Service被杀死后，系统不会自动重启该Service
        return START_NOT_STICKY
    }
}